<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        @returnBack="$emit('returnModify')"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :label-width="formInfo.labelWidth"
              :rules="formInfo.rules"
            >
              <template v-slot:form-patrolRouteName>
                <el-input
                  v-model="formInfo.data.patrolRouteName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择巡检路线"
                >
                  <template #append>
                    <el-icon @click="_selectPatrolRoute"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-execResponseUserName>
                <el-input
                  v-model="formInfo.data.execResponseUserName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择执行负责人"
                >
                  <template #append>
                    <el-icon @click="selectExecResponseUser"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-execCoordinationUserName>
                <el-input
                  v-model="formInfo.data.execCoordinationUserName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择执行协同人"
                >
                  <template #append>
                    <el-icon @click="selectExecCoordinationUser"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-remindDuration>
                <div class="flex">
                  <el-input-number
                    v-model="formInfo.data.remindDuration"
                    style="width: 65%"
                    controls-position="right"
                    :min="0"
                    placeholder="请输入内容"
                    type="number"
                    class="flex-input"
                  >
                  </el-input-number>
                  <select-model
                    v-model="formInfo.data.remindTimeType"
                    type-code="remind_time_type"
                    :check-default="false"
                    :clearable="false"
                    style="width: 35%"
                    class="flex-select"
                  />
                </div>
              </template>
              <template v-slot:form-createDuration>
                <div class="flex">
                  <el-input-number
                    v-model="formInfo.data.createDuration"
                    style="width: 65%"
                    controls-position="right"
                    :min="0"
                    placeholder="请输入内容"
                    class="flex-input"
                  >
                  </el-input-number>
                  <select-model
                    v-model="formInfo.data.createTimeType"
                    type-code="remind_time_type"
                    :check-default="false"
                    :clearable="false"
                    style="width: 35%"
                    class="flex-select"
                  />
                </div>
              </template>
              <template v-slot:form-execInterval>
                <div class="flex" style="width: 405px">
                  <el-input-number
                    v-model="formInfo.data.execInterval"
                    style="width: 65%"
                    controls-position="right"
                    :min="1"
                    placeholder="请输入内容"
                    class="flex-input"
                  >
                  </el-input-number>
                  <select-model
                    v-model="formInfo.data.execIntervalType"
                    type-code="exec_interval_type"
                    :check-default="false"
                    :clearable="false"
                    style="width: 35%"
                    class="flex-select"
                    @change="execIntervalTypChange"
                  />
                </div>
              </template>

              <template v-slot:form-execMoment>
                <el-select
                  v-model="formInfo.data.execMoment"
                  clearable
                  placeholder="请选择时间"
                >
                  <el-option
                    v-for="item in formInfo.execMomentOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </template>
              <template v-slot:form-weekDays>
                <el-checkbox-group
                  key="weekDays"
                  v-model="formInfo.data.weekDays"
                >
                  <el-checkbox-button
                    v-for="(item, index) in formInfo.weekDayOptions"
                    :key="index"
                    class="patrolPlan-checkbox"
                    :label="item.value"
                    >{{ item.label }}</el-checkbox-button
                  >
                </el-checkbox-group>
              </template>
              <template v-slot:form-mouthDays>
                <el-checkbox-group
                  key="mouthDays"
                  v-model="formInfo.data.mouthDays"
                  style="width: 375px"
                >
                  <el-checkbox-button
                    v-for="(item, index) in formInfo.mountDayOptions"
                    :key="index"
                    class="patrolPlan-checkbox"
                    :label="item"
                    >{{ item }}</el-checkbox-button
                  >
                </el-checkbox-group>
              </template>
            </page-form>
          </div>
        </div>
      </NewFullScreen>
      <select-patrol-route
        v-if="selectPatrolRouteInfo.visible"
        v-model:show-dialog="selectPatrolRouteInfo.visible"
        :exclude-query-list="selectPatrolRouteInfo.excludeQueryList"
        :query="selectPatrolRouteInfo.query"
        :check-box="false"
        :highlight-row="true"
        @callback="selectPatrolRouteCallBack"
      />
      <SelectUsers
        v-if="execResponseUserInfo.visible"
        v-model:show-dialog="execResponseUserInfo.visible"
        :query="execResponseUserInfo.query"
        :api="execResponseUserInfo.api"
        :check-box="false"
        :highlight-row="true"
        @callback="selectExecResponseUserBack"
      />
      <SelectUsers
        v-if="execCoordinationUserInfo.visible"
        v-model:show-dialog="execCoordinationUserInfo.visible"
        :query="execCoordinationUserInfo.query"
        :api="execCoordinationUserInfo.api"
        :check-box="true"
        :save-empty="true"
        :highlight-row="false"
        :checked-row-list="execCoordinationUserInfo.checkedRowList"
        @callback="selectExecCoordinationUserBack"
      />
    </div>
  </div>
</template>

<script setup name="BrandModify">
import PageForm from '@/components/PageForm/index'

import selectPatrolRoute from '@/components/SelectPatrolRoute/index'
import SelectUsers from '@/components/SelectUsers/index'
import { getRrgUserList, getDeptUserAll } from '@/api/base'
import { creatPlan, updatePlan, getPlanById } from '@/api/patrol.js'
import SelectModel from '@/components/SelectModel/index'
import commonJson from '@/common/js/commonJson.js'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'id', 'title'])

const formInfo = reactive({
  ref: null,
  data: {
    execIntervalType: '1',
    remindTimeType: '1',
    createTimeType: '1',
    execMoment: '',
    weekDays: [],
    mouthDays: [],
  },
  fieldList: [
    { label: '计划名称', value: 'patrolPlanName', type: 'input' },
    {
      label: '巡检路线',
      value: 'patrolRouteName',
      type: 'slot',
    },
    {
      label: '开始日期',
      value: 'startDate',
      type: 'date',
    },
    {
      label: '终止日期',
      value: 'endDate',
      type: 'date',
      TimePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        },
      },
    },
    {
      label: '执行负责人',
      value: 'execResponseUserName',
      type: 'slot',
    },
    {
      label: '执行协同人',
      value: 'execCoordinationUserName',
      type: 'slot',
    },
    {
      label: '执行间隔',
      value: 'execInterval',
      type: 'slot',
      className: 'not-br',
    },
    {
      label: '每周的',
      value: 'weekDays',
      type: 'slot',
      show: false,
      className: 'not-br',
    },
    {
      label: '每月的',
      value: 'mouthDays',
      type: 'slot',
      show: false,
      className: 'not-br',
    },
    {
      label: '时间为',
      value: 'execMoment',
      type: 'slot',
    },

    {
      label: '生成于',
      value: 'createDuration',
      labelTip: '生成时间必须早于提醒时间5分钟',
      type: 'slot',
    },
    {
      label: '提醒于',
      labelTip: '提醒于任务开始前',
      value: 'remindDuration',
      type: 'slot',
    },
    {
      label: '工作时长(分钟)',
      value: 'workTime',
      type: 'number',
    },
    {
      label: '允许超时(分钟)',
      value: 'allowTimeout',
      type: 'number',
    },

    //{
    //  label: "备注",
    //  value: "remark",
    //  type: "textarea",
    //  className: "not-br"
    //}
  ],
  rules: {
    patrolPlanName: [
      { required: true, message: '请输入计划名称', trigger: 'blur' },
    ],
    startDate: [
      { required: true, message: '请选择开始日期', trigger: 'change' },
    ],
    execInterval: [
      { required: true, message: '请输入执行间隔', trigger: 'blur' },
    ],
    createDuration: [
      { required: true, message: '请输入生成时间', trigger: 'blur' },
    ],
    remindDuration: [
      { required: true, message: '请输入提醒时间', trigger: 'blur' },
    ],
    patrolRouteName: [
      { required: true, message: '请选择巡检线路', trigger: 'change' },
    ],
    execResponseUserName: [
      { required: true, message: '请选择执行负责人', trigger: 'change' },
    ],
    execMoment: [{ required: true, message: '请选择时间', trigger: 'change' }],
    weekDays: [{ required: true, message: '请选择周', trigger: 'change' }],
    mouthDays: [{ required: true, message: '请选择月', trigger: 'change' }],
  },
  execMomentOptions: commonJson.execMomentOptions,
  mountDayOptions: commonJson.mountDayOptions,
  weekDayOptions: commonJson.weekDayOptions,
  labelWidth: '120px',
})
const fullInfo = reactive({
  btnList: [{ label: '保存', event: save, show: true }],
})
const selectPatrolRouteInfo = reactive({
  visible: false,
  excludeQueryList: [],
  query: {
    customizeUserVO: {},
    queryMap: {},
    queryParams: {},
  },
})
const execResponseUserInfo = reactive({
  visible: false,
  api: getRrgUserList,
  type: '',
  query: {
    hasAllDept: 1,
  },
  row: {},
})
const execCoordinationUserInfo = reactive({
  visible: false,
  api: getRrgUserList,
  type: '',
  checkedRowList: [],
  query: {
    hasAllDept: 1,
  },
  row: {},
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

onMounted(() => {
  if (props.id) {
    getDetails()
  }
})

function execIntervalTypChange(val) {
  //间隔时间天周月切换
  formInfo.data.execInterval = undefined
  if (val === '1') {
    showFieldListItem(false, 'weekDays')
    showFieldListItem(false, 'mouthDays')
    formInfo.data.weekDays = []
    formInfo.data.mouthDays = []
  } else if (val === '2') {
    showFieldListItem(true, 'weekDays')
    showFieldListItem(false, 'mouthDays')
    formInfo.data.mouthDays = []
    proxy.$nextTick(() => {
      formInfo.ref.clearValidate('weekDays')
    })
  } else if (val === '3') {
    showFieldListItem(false, 'weekDays')
    showFieldListItem(true, 'mouthDays')
    formInfo.data.weekDays = []
    proxy.$nextTick(() => {
      formInfo.ref.clearValidate('mouthDays')
    })
  }
}
function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.fieldList
  fieldList.map((item) => {
    if (item.value === nameValue) {
      item.show = show
    }
  })
}
function _selectPatrolRoute() {
  //巡检路线
  selectPatrolRouteInfo.visible = true
}
function selectPatrolRouteCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.data['patrolRouteId'] = data.id
    formInfo.data['patrolRouteName'] = data.routeName
    formInfo.data['execResponseUser'] = data.routeResponseUser
    formInfo.data['execResponseUserName'] = data.routeResponseUserName
  } else {
    formInfo.data['patrolRouteId'] = ''
    formInfo.data['patrolRouteName'] = ''
    formInfo.data['execResponseUser'] = ''
    formInfo.data['execResponseUserName'] = ''
  }
}
function selectExecResponseUser() {
  //执行负责人
  execResponseUserInfo.visible = true
}
function selectExecResponseUserBack(data) {
  if (data && data.id) {
    formInfo.data['execResponseUser'] = data.id
    formInfo.data['execResponseUserName'] = data.name
  } else {
    formInfo.data['execResponseUser'] = ''
    formInfo.data['execResponseUserName'] = ''
  }
}
function selectExecCoordinationUser() {
  //执行协同人
  execCoordinationUserInfo.visible = true
}
function selectExecCoordinationUserBack(data) {
  if (data && data.length) {
    let ids = data.map((item) => item.id)
    let names = data.map((item) => item.name)
    formInfo.data['execCoordinationUser'] = ids.toString()
    formInfo.data['execCoordinationUserName'] = names.toString()
    execCoordinationUserInfo.checkedRowList = data
  } else {
    formInfo.data['execCoordinationUser'] = ''
    formInfo.data['execCoordinationUserName'] = ''
    execCoordinationUserInfo.checkedRowList = ''
  }
}

function save() {
  
  formInfo.ref.validate((valid) => {
    if (valid) {
      if (!getDuration()) {
        return
      }
      let endDate = formInfo.data.endDate
      let startDate = formInfo.data.startDate
      if (endDate) {
        let fmartStartDate = new Date(startDate)
        let fmartEndDate = new Date(endDate)
        if (fmartEndDate.getTime() < fmartStartDate.getTime()) {
          proxy.$message({
            showClose: true,
            message: '终止日期不能大于开始日期',
            type: 'error',
            duration: 3500,
          })
          return
        }
      }
      let api = props.id ? updatePlan : creatPlan
      if (formInfo.data.weekDays.length) {
        formInfo.data.weekDays.sort((a, b) => a - b)
        formInfo.data.weekDays = formInfo.data.weekDays.toString()
      } else {
        formInfo.data.weekDays = ''
      }
      if (formInfo.data.mouthDays.length) {
        formInfo.data.mouthDays.sort((a, b) => a - b)
        formInfo.data.mouthDays = formInfo.data.mouthDays.toString()
      } else {
        formInfo.data.mouthDays = ''
      }
      api(formInfo.data).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          emit('returnModify')
        }
      })
    }
  })
}
function getDuration() {
  //createDuration createTimeType,remindDuration remindTimeType 1分2时3天
  const data = formInfo.data
  let createDurationTime = getMins(data.createTimeType, data.createDuration)
  let remindDurationTime = getMins(data.remindTimeType, data.remindDuration)
  let subtr = proxy.$fn.Subtr(createDurationTime, remindDurationTime)
  if (subtr < 5) {
    proxy.$message({
      message: `计划生成时间必须早于提醒时间5分钟`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return false
  } else {
    return true
  }
}
function getMins(type, val) {
  //天时分转分
  if (type == 1) {
    return val
  } else if (type == 2) {
    return proxy.$fn.accMul(val || 0, 60)
  } else if (type == 3) {
    return proxy.$fn.accMul(val || 0, 1440)
  }
}
function getUserAllList(ids) {
  let params = {
    idIn: ids,
  }
  getDeptUserAll(params).then((res) => {
    if (res && res.success) {
      execCoordinationUserInfo.checkedRowList = res.data
    }
  })
}
function getDetails() {
  getPlanById(props.id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      data.weekDays = proxy.$fn.splitArr(data.weekDays)
      data.mouthDays = proxy.$fn.splitArr(data.mouthDays)
      if (data.weekDays.length) {
        data.weekDays = data.weekDays.map((item) => Number(item))
      }
      if (data.mouthDays.length) {
        data.mouthDays = data.mouthDays.map((item) => Number(item))
      }
      if (data.execCoordinationUser) {
        getUserAllList(data.execCoordinationUser)
      }
      formInfo.data = data
      if (resp.data.execIntervalType == '1') {
        showFieldListItem(false, 'weekDays')
        showFieldListItem(false, 'mouthDays')
      } else if (resp.data.execIntervalType == '2') {
        showFieldListItem(true, 'weekDays')
        showFieldListItem(false, 'mouthDays')
      } else if (resp.data.execIntervalType == '3') {
        showFieldListItem(false, 'weekDays')
        showFieldListItem(true, 'mouthDays')
      }
    }
  })
}
</script>

<style scoped lang="scss">
.flex {
  display: flex;
  // flex: 1;
}
.flex-select :deep(.el-input--small .el-input__inner) {
  height: 28px !important;
}
:deep(.patrolPlan-checkbox) {
  padding: 0 5px 5px 5px;
  box-sizing: border-box;
  .el-checkbox-button__inner {
    width: 30px;
    height: 30px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
:deep(.el-checkbox-button__inner) {
  border: 1px solid #dcdfe6 !important;
}
</style>
